package com.huawei.knowledge.doc.service.md;

import com.huawei.knowledge.utils.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.pegdown.PegDownProcessor;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/4/29/029.
 */
public class MarkToHtml {

    private static Logger myLogger = LogManager.getLogger(MarkToHtml.class);

    private String markDown;

    private String docDir;

    private String htmlStr;

    public MarkToHtml(String markDown, String docDir) {
        this.markDown = markDown;
        this.docDir = docDir;
    }

    /**
     * 执行转换
     *
     * @return 转换结果
     */
    public String mkToHtml() {
        PegDownProcessor pdp = new PegDownProcessor(Integer.MAX_VALUE);
        htmlStr = pdp.markdownToHtml(markDown);
        afterChange();
        return htmlStr;
    }

    private void afterChange() {
        //处理img对象，转换成base64
        Pattern p = Pattern.compile("<img src=\"([\\S]*)\".*/>");
        Matcher m = p.matcher(htmlStr);
        if (m.find()) {
            String imgStr = m.group(1);
            String imgPath = docDir + File.separator + imgStr;
            //转换成base64
            String imgBase64 = getImageStrFromPath(imgPath);
            String imgType = imgStr.substring(imgStr.lastIndexOf(".") + 1);
            StringBuilder imgTag = new StringBuilder("<img src=\"data:image/");
            imgTag.append(imgType);
            imgTag.append(";base64,");
            imgTag.append(imgBase64);
            imgTag.append("\"/>");
            htmlStr = m.replaceFirst(imgTag.toString());
            afterChange();
            myLogger.info("img : " + imgPath + "convert to base64");
        }
    }

    private String getImageStrFromPath(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            myLogger.error("getImageStrFromPath has error : ",e);
        }finally{
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    myLogger.error("getImageStrFromPath has error : ",e);
                }
            }
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }
}
